package com.etheart.lyric.htmlparser.service.baidu;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.springframework.stereotype.Service;

import com.etheart.framework.core.util.RegexUtils;
import com.etheart.lyric.htmlparser.util.HtmlparserUtils;

@Service("htmlparser_BaiduSingerListParseService")
public class BaiduSingerListParseService {
	
	public List<String> parseSingerListPage(File singerListFile) throws ParserException, IOException{
		Parser parser = HtmlparserUtils.getParser(singerListFile);
		List<String> singerUrlList = new ArrayList<String>(100);
			NodeFilter nodeFilter = new AndFilter(new TagNameFilter("ul"),new HasAttributeFilter("class", "single-line"));
			NodeList nodeList = parser.parse(nodeFilter);
			for (int i = 0; i < nodeList.size(); i++) {
				Node node = nodeList.elementAt(i);
				//得到所有的li标签
				NodeList list = node.getChildren();
				for (int j = 0; j < list.size(); j++) {
					String liHtml = list.elementAt(j).toHtml();
					if (StringUtils.isBlank(liHtml)) {
						continue;
					}
					String href = getSingerUrlFromA(liHtml);
					singerUrlList.add(href)	;
				}
			}
		return singerUrlList;
	}

	private String getSingerUrlFromA(String a) {
          return RegexUtils.getMatcheGroup(".*href=\"([^\"]*)\".*", a);
	}

	public String parseTitle(File file, String fileEncode, String charset,
			String baseUrl) throws ParserException, IOException {
		String fileString = FileUtils.readFileToString(file, fileEncode);
		return parseTitle(fileString,charset);
	}

	private String parseTitle(String html, String charset) throws ParserException {
		Parser parser = Parser.createParser(html, charset);
		
			NodeFilter nodeFilter = new TagNameFilter("title");
			NodeList nodeList = parser.parse(nodeFilter);
			Tag tag = (Tag) nodeList.elementAt(0);
			return tag.toPlainTextString();
			
	}
	
	
}
